<template>
  <div>
    <el-card>
      <el-row>
        <el-space wrap>
          <el-button
            type="primary"
            :icon="Plus"
            @click="toCreate()"
            v-button="['api:message:emailtemplate:create']"
          >
            新增
          </el-button>
          <el-button
            type="primary"
            :icon="Download"
            @click="exportExcel()"
            v-button="['api:message:emailtemplate:exportexcel']"
          >
            导出
          </el-button>
          <el-upload
            class="upload"
            v-button="['api:message:emailtemplate:importexcel']"
            :show-file-list="false"
            :http-request="importExcel"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <el-button :icon="Upload" type="primary">导入</el-button>
          </el-upload>
        </el-space>
      </el-row>
      <el-row>
        <el-table
          :data="tableList"
          :border="true"
          style="width: 100%"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <el-table-column prop="name" label="模板名称" width="180" />
          <el-table-column prop="subject" label="主题" />
          <el-table-column prop="bccEmailAddresses" label="抄送邮箱" />
          <el-table-column prop="email" label="发送邮箱" />
          <el-table-column prop="isActive" label="状态">
            <template #default="scope">
              <el-switch v-model="scope.row.isActive" :disabled="true" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                type="primary"
                :icon="Promotion"
                @click="toSend(scope.row)"
                v-button="['api:message:emailtemplate:querydefaultjson']"
              >
                测试发送
              </el-button>
              <el-button
                type="primary"
                :icon="EditPen"
                @click="toEdit(scope.row)"
                v-button="['api:message:emailtemplate:update']"
              >
                修改
              </el-button>
              <el-popconfirm title="确定要删除这条数据?" @confirm="toDelete(scope.row)">
                <template #reference>
                  <el-button
                    type="danger"
                    :icon="Delete"
                    v-button="['api:message:emailtemplate:delete']"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <Pagination
          :total="search.total"
          v-model:pageIndex="search.pageIndex"
          v-model:pageSize="search.pageSize"
          @change="query()"
        ></Pagination>
      </el-row>
    </el-card>

    <!-- 新增和修改弹框 -->
    <el-dialog
      v-model="dialogVisible"
      title="邮件模板"
      width="1000"
      :draggable="true"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="name">
              <el-input placeholder="模板名称" v-model="form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据源" prop="variableClass">
              <el-select
                v-model="form.variableClass"
                placeholder="请选择"
                @change="variableClassChange"
              >
                <el-option
                  v-for="item in variableClassList"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item prop="variable">
              <template #label>
                <div class="flex-y-center">
                  模板变量
                  <el-tooltip placement="bottom" effect="dark">
                    <template #content>点击复制模板变量</template>
                    <i-ep-QuestionFilled />
                  </el-tooltip>
                </div>
              </template>
              <div class="flex gap-2 flex-wrap">
                <el-tag
                  :hit="false"
                  type="primary"
                  v-for="item in variableList"
                  @click="copy(item.value)"
                >
                  {{ item.text }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="主题" prop="subject">
              <el-input placeholder="主题" v-model="form.subject" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="抄送邮箱" prop="bccEmailAddresses">
              <el-input placeholder="抄送邮箱" v-model="form.bccEmailAddresses" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发送邮箱" prop="emailAccountId">
              <el-select v-model="form.emailAccountId" placeholder="请选择">
                <el-option
                  v-for="item in accountSelect"
                  :key="item.id"
                  :label="item.email"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isActive">
              <el-radio-group v-model="form.isActive">
                <el-radio :value="true">启用</el-radio>
                <el-radio :value="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <editor v-model="form.body" />
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save()">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 测试发送 -->
    <el-dialog
      v-model="dialogSend"
      title="测试发送"
      :draggable="true"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px" ref="sendDataFormRef" :model="sendDataForm">
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="收件人邮箱"
              prop="toEmailAddress"
              :rules="[
                {
                  required: true,
                  message: 'Please input email address',
                  trigger: 'blur',
                },
                {
                  type: 'email',
                  message: 'Please input correct email address',
                  trigger: ['blur', 'change'],
                },
              ]"
            >
              <el-input placeholder="收件人邮箱" v-model="sendDataForm.toEmailAddress" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件人名称" prop="toEmailName">
              <el-input placeholder="收件人名称" v-model="sendDataForm.toEmailName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="测试数据" prop="emailData">
              <el-input
                v-model="sendDataForm.emailData"
                :autosize="{ minRows: 5, maxRows: 50 }"
                type="textarea"
                placeholder="Please input"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogSend = false">取消</el-button>
          <el-button
            type="primary"
            @click="sendEmail(sendDataFormRef)"
            v-button="['api:message:emailtemplate:testsendemail']"
          >
            发送邮件
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus, Delete, EditPen, Promotion, Download, Upload } from "@element-plus/icons-vue";
import EmailTemplateApi, {
  EmailTemplateEdit,
  EmailTemplateModel,
  EmailTemplateQuery,
  TemplateVariableModel,
  TestSendEmailParam,
} from "@/api/message/email/emailTemplate";
import { EditEnum } from "@/enums/EditEnum";
import Editor from "@/components/WangEditor/index.vue";
import useClipboard from "vue-clipboard3";
import EmailAccountApi, { EmailAccountSelect } from "@/api/message/email/emailAccount";
import { FormInstance, UploadRequestOptions } from "element-plus";
import successMsg from "@/utils/successMsg";
import { saveAsExcel } from "@/utils/saveAsUtils";
defineOptions({
  name: "emailtemplate",
  inherititems: false,
});
const { toClipboard } = useClipboard();

const tableList = ref<EmailTemplateModel[]>();

//查询条件
const search = reactive<EmailTemplateQuery>({
  searchString: "",
  total: 0,
  pageIndex: 1, //第几页
  pageSize: 10, //每页多少条
});

onMounted(async () => {
  await query();
});

const query = async () => {
  const { dataList, totalCount } = await EmailTemplateApi.query(search);
  search.total = totalCount;
  tableList.value = dataList;
};

const form = ref<EmailTemplateEdit>({
  variableClass: "",
});
const dialogVisible = ref(false);
const editType = ref<EditEnum>();
const variableClassList = ref<TemplateVariableModel[]>();
const variableList = ref<TemplateVariableModel[]>();
const accountSelect = ref<EmailAccountSelect[]>();
const toEdit = async (row: EmailTemplateEdit) => {
  editType.value = EditEnum.update;
  dialogVisible.value = true;
  form.value = { ...row };

  variableClassList.value = await EmailTemplateApi.queryVariableClass();
  variableList.value = await EmailTemplateApi.queryVariable(form.value.variableClass);
  accountSelect.value = await EmailAccountApi.queryAccountSelect();
};

const toCreate = async () => {
  editType.value = EditEnum.create;
  dialogVisible.value = true;
  form.value = {
    isActive: true,
    variableClass: "",
  };

  variableClassList.value = await EmailTemplateApi.queryVariableClass();
  accountSelect.value = await EmailAccountApi.queryAccountSelect();
};

const exportExcel = async () => {
  const response = await EmailTemplateApi.exportExcel();
  saveAsExcel(response);
};

const importExcel = async (options: UploadRequestOptions) => {
  const { success, message } = await EmailTemplateApi.importExcel(options.file);
  successMsg(success, message, async () => {
    await query();
  });
};

const variableClassChange = async (value: string) => {
  variableList.value = await EmailTemplateApi.queryVariable(form.value.variableClass);
};

/** 复制 */
const copy = async (value: string) => {
  try {
    await toClipboard(value);
    ElMessage({
      message: "已复制！",
      type: "success",
    });
  } catch (e) {
    ElMessage({
      message: "复制失败！",
      type: "error",
    });
  }
};

const save = async () => {
  const { success, message } = await EmailTemplateApi[EditEnum[editType.value]](form.value);
  successMsg(success, message, async () => {
    dialogVisible.value = false;
    await query();
  });
};

const toDelete = async (row: EmailTemplateModel) => {
  const { success, message } = await EmailTemplateApi.delete(row.id);
  successMsg(success, message, await query());
};

const sendDataFormRef = ref<FormInstance>();
const dialogSend = ref(false);
const sendDataForm = ref<TestSendEmailParam>({});
const toSend = async (row: EmailTemplateModel) => {
  dialogSend.value = true;

  const { json } = await EmailTemplateApi.queryDefaultJson(row.variableClass);
  sendDataForm.value.emailData = JSON.stringify(JSON.parse(json), null, "\t");
  sendDataForm.value.id = row.id;
};

const sendEmail = async (formEl: FormInstance) => {
  formEl.validate(async (valid) => {
    if (valid) {
      const { success, message } = await EmailTemplateApi.testSendEmail(sendDataForm.value);
      successMsg(success, message, async () => {
        dialogSend.value = false;
        await query();
      });
    }
  });
};
</script>

<style scoped>
.el-tag:hover {
  cursor: pointer;
  border-color: var(--el-tag-hover-color);
}
.upload {
  display: flex;
}
</style>
